package com.huika.dealontop.control.pay.activity;

import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.pay.utils.BasePay;
import com.huika.dealontop.control.pay.utils.OmisePay;
import com.huika.dealontop.support.domain.OmisePayResultBean;
import com.huika.dealontop.support.domain.UserModel;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.views.PromptOperatDialog;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.dealontop.views.ToastMsg;
import com.huika.dealontop.views.cleardit.ClearableEditText;
import com.huika.dealontop.views.wheelview.OnWheelScrollListener;
import com.huika.dealontop.views.wheelview.WheelView;
import com.huika.dealontop.views.wheelview.adapter.NumericWheelAdapter;
import com.huika.huikalib.utils.MoneyShowTool;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import co.omise.Card;
import co.omise.Omise;
import co.omise.OmiseException;
import co.omise.RequestTokenCallback;
import co.omise.Token;
import co.omise.TokenRequest;

/**
 * Description:Omise支付页面
 * Created by zhouweiyong on 2015/11/20.
 */
public class OmisePayActivity extends BaseAct {
    private TextView tv_order_num_pac, tv_phone_pac, tv_total_money_pac;
    private ClearableEditText et_user_name_apo, et_card_num_apo, et_validity_apo, et_security_code_apo;
    private Button btn_pac;
    private LinearLayout layout_phone_pac;
    private String paymentOrderID;
    private String orderId;
    private boolean needCloseCurrentPage;
    private double totalMoney;
    private int mYear = 1996;
    private WheelView year;
    private WheelView month;
    private UserModel userModel;
    private int currentYear;
    private int currentMonth;
    private String phone;
    private String userId;

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            paymentOrderID = intent.getStringExtra(BasePay.PAYORDERNO);
            needCloseCurrentPage = intent.getBooleanExtra(BasePay.NEEDCLOSECURRENTPAGE, false);
            totalMoney = intent.getDoubleExtra(BasePay.TOTALMONEY, 0);
            orderId = intent.getStringExtra(BasePay.ORDERNO);
            phone = intent.getStringExtra(BasePay.PHONE);
            userId = intent.getStringExtra(BasePay.USERID);
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_pay_omise);
    }


    @Override
    protected void initWidget() {
        TitleBarHelper titleBarHelper = new TitleBarHelper(this, R.string.title_omise_pay);
        titleBarHelper.setLeftMsg("");
        layout_phone_pac = (LinearLayout) findViewById(R.id.layout_phone_pac);
        tv_order_num_pac = (TextView) findViewById(R.id.tv_order_num_pac);
        tv_phone_pac = (TextView) findViewById(R.id.tv_phone_pac);
        tv_total_money_pac = (TextView) findViewById(R.id.tv_total_money_pac);
        et_user_name_apo = (ClearableEditText) findViewById(R.id.et_user_name_apo);
        et_card_num_apo = (ClearableEditText) findViewById(R.id.et_card_num_apo);
        et_validity_apo = (ClearableEditText) findViewById(R.id.et_validity_apo);
        et_security_code_apo = (ClearableEditText) findViewById(R.id.et_security_code_apo);
        btn_pac = (Button) findViewById(R.id.btn_pac);
        et_validity_apo.setOnClickListener(this);
        btn_pac.setOnClickListener(this);
        et_user_name_apo.addTextChangedListener(new MyWatcher(et_user_name_apo));
        et_card_num_apo.addTextChangedListener(new MyWatcher(et_card_num_apo));
        et_validity_apo.addTextChangedListener(new MyWatcher(et_validity_apo));
        et_security_code_apo.addTextChangedListener(new MyWatcher(et_security_code_apo));
        tv_order_num_pac.setText(orderId);
        userModel = GlobalApp.userModel;
        if (!TextUtils.isEmpty(phone)) {
            tv_phone_pac.setText(String.format("%s****%s", phone.substring(0, 3), phone.substring(7, 10)));
        } else {
            layout_phone_pac.setVisibility(View.GONE);
        }
        tv_total_money_pac.setText(String.format(getString(R.string.common_money), MoneyShowTool.twolastDF(totalMoney)));
        checkInput(et_user_name_apo, et_card_num_apo, et_security_code_apo, et_validity_apo);
    }


    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.et_validity_apo:
                selectValidDate();
                break;
            case R.id.btn_pac:
                getToken(getInputStr(et_user_name_apo), getInputStr(et_card_num_apo).replaceAll(" ", ""), String.valueOf(currentMonth), String.valueOf(currentYear), getInputStr(et_security_code_apo), "", "");
                break;
        }
    }


    private void selectValidDate() {
        String date = getInputStr(et_validity_apo);
        String pattern = "(\\d{2})\\/(\\d{4})";
        int cYear = 0;
        int cMonth = 0;
//        if ("1".equals(getString(R.string.common_lang))) {
//            pattern = "(\\d{4})\\D+(\\d{1})\\D+";
//        } else {
//            pattern = "\\D+(\\d{1})\\D+(\\d{4})";
//        }
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(date);
//        if (m.find()) {
//            if ("1".equals(getString(R.string.common_lang))){
//                cYear = Integer.parseInt(m.group(1));
//                cMonth = Integer.parseInt(m.group(2));
//            }else{
//                cMonth = Integer.parseInt(m.group(1));
//                cYear = Integer.parseInt(m.group(2));
//            }
//        }
        if (m.find()) {
            cMonth = Integer.parseInt(m.group(1));
            cYear = Integer.parseInt(m.group(2));
        }


        Calendar c = Calendar.getInstance();
        int tYear = c.get(Calendar.YEAR);
        int tMonth = c.get(Calendar.MONTH);
        View view = View.inflate(this, R.layout.dialog_pay_valid_date, null);
        year = (WheelView) view.findViewById(R.id.year);
        month = (WheelView) view.findViewById(R.id.month);
        NumericWheelAdapter numericWheelAdapter1 = new NumericWheelAdapter(this, 1950, 2050);
        //numericWheelAdapter1.setLabel(getString(R.string.pay_year));
        numericWheelAdapter1.setLabel("");
        year.setViewAdapter(numericWheelAdapter1);
        year.setCyclic(true);
        if (cYear != 0) {
            year.setCurrentItem(cYear - 1950);
        } else {
            year.setCurrentItem(tYear - 1950);
        }
        year.addScrollingListener(scrollListener);

        NumericWheelAdapter numericWheelAdapter2 = new NumericWheelAdapter(this, 1, 12, "%02d");
       // numericWheelAdapter2.setLabel(getString(R.string.pay_month));
        numericWheelAdapter2.setLabel("");
        month.setViewAdapter(numericWheelAdapter2);
        month.setCyclic(true);
        if (cMonth != 0) {
            month.setCurrentItem(cMonth - 1);
        } else {
            month.setCurrentItem(tMonth - 0);
        }
        month.addScrollingListener(scrollListener);

        final PromptOperatDialog dialog_lang = new PromptOperatDialog(OmisePayActivity.this, view);
        dialog_lang.setTitleGone();
        dialog_lang.setCenterLineGone();
        dialog_lang.setCancelBtnGone();
        dialog_lang.getConfirmBtn().setText(getString(R.string.register_confirm));
        dialog_lang.setConfirmClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCurrentValidity();
                dialog_lang.dismiss();
            }
        });
        dialog_lang.show();
    }


    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {
        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            getCurrentValidity();
        }
    };

    private void getCurrentValidity() {
        currentYear = year.getCurrentItem() + 1950;
        currentMonth = month.getCurrentItem() + 1;
        String validDate = new StringBuffer().append(String.format("%02d", (month.getCurrentItem() + 1))).append("/").append(year.getCurrentItem() + 1950).toString();
//        if ("1".equals(getString(R.string.common_lang))){
//            validDate = new StringBuffer().append(year.getCurrentItem() + 1950).append(getString(R.string.pay_year)).append(month.getCurrentItem() + 1).append(getString(R.string.pay_month)).toString();
//        }else{
//            validDate = new StringBuffer().append(getString(R.string.pay_month)).append(month.getCurrentItem() + 1).append(getString(R.string.pay_year)).append(year.getCurrentItem() + 1950).toString();
//        }
        et_validity_apo.setText(validDate);
    }

    /**
     * @description：获取支付token
     * @author zc
     * @date 2015年8月20日 下午5:28:30
     */
    private void getToken(String name, String cardNumber,
                          String expirationMonth, String expirationYear, String securityCode,
                          String city, String postalCode) {
        TokenRequest tokenRequest = new TokenRequest();

        tokenRequest.setPublicKey(OmisePay.publicKey);
        Card card = new Card();
        card.setName(name);
        // card.setCity(city);
        // card.setPostalCode(postalCode);
        String tempCardNumber = cardNumber.replaceAll(" ", "");
        card.setNumber(tempCardNumber);
        card.setExpirationMonth(expirationMonth);
        card.setExpirationYear(expirationYear);
        card.setSecurityCode(securityCode);
        if (UrlConstants.isReleaseEnvironment()) {
            card.setSecurityCodeCheck(true);
        }
        tokenRequest.setCard(card);

        Omise omise = new Omise();

        try {

            omise.requestToken(tokenRequest, requestTokenCallback);
        } catch (OmiseException e) {
            e.printStackTrace();
        }
        showLoadingDialog("");
    }

    private RequestTokenCallback requestTokenCallback = new RequestTokenCallback() {
        @Override
        public void onRequestSucceeded(final Token token) {
            paymentNet(token.getId());
        }

        @Override
        public void onRequestFailed(final int errorCode) {
            handler.sendEmptyMessage(0x001);
        }
    };

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            dismissLoadingDialog();
            switch (msg.what) {
                case 0x001:
                    ToastMsg.showToastMsg(OmisePayActivity.this, R.string.pay_error_msg);
                    break;
                default:
                    Intent intent = new Intent(OmisePayActivity.this, PayFailActivity.class);
                    showActivity(OmisePayActivity.this, intent);
                    OmisePayActivity.this.finish();
                    break;
            }

        }

        ;
    };

    //10724412094
    private void paymentNet(String token) {
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        UserModel userModel = GlobalApp.userModel;
        ajaxParams.putCommonTypeParam("userId", userId);
        ajaxParams.putCommonTypeParam("paymentOrderId", paymentOrderID);
        ajaxParams.putCommonTypeParam("omiseToken", token);
        ajaxParams.putCommonTypeParam("amount", totalMoney);
        FormResultRequest<OmisePayResultBean> request = new FormResultRequest<OmisePayResultBean>(UrlConstants.OMISEPAYMENT, new Response.Listener<RequestResult<OmisePayResultBean>>() {

            @Override
            public void onResponse(RequestResult<OmisePayResultBean> arg0) {
                dismissLoadingDialog();
                //进入支付成功页面
                Intent intent = new Intent(OmisePayActivity.this, PaySuccessActivity.class);
                intent.putExtra(Constants.PAY_ORDERID, orderId);
                intent.putExtra(Constants.OMISE_PAY_RESULT, arg0.getRs());
                intent.putExtra(Constants.PAY_PAYMENTORDERID, paymentOrderID);
                intent.putExtra(BasePay.PHONE, phone);
                showActivity(OmisePayActivity.this, intent);
                OmisePayActivity.this.finish();
            }
        }, this, new TypeToken<RequestResult<OmisePayResultBean>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        super.onErrorResponse(error);
        Intent intent = new Intent(OmisePayActivity.this, PayFailActivity.class);
        showActivity(OmisePayActivity.this, intent);
        OmisePayActivity.this.finish();
    }

    class MyWatcher implements TextWatcher {

        EditText mEditText;

        public MyWatcher(EditText mEditText) {
            this.mEditText = mEditText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            checkInput(et_user_name_apo, et_card_num_apo, et_security_code_apo, et_validity_apo);
            if (mEditText.getId() == et_card_num_apo.getId()) {
                String trimSpaceStr = s.toString().replaceAll(" ", "");
                if (before <= 0) {
                    int trimSpaceLength = trimSpaceStr.length();
                    if (null != s && trimSpaceLength > 0 && trimSpaceLength < 16) {
                        String contentStr = "";
                        for (int index = 0; index < trimSpaceLength; index++) {
                            if (trimSpaceStr.charAt(index) != ' ' && (index + 1) % 4 == 0) {
                                contentStr += trimSpaceStr.charAt(index) + "  ";
                            } else {
                                contentStr += trimSpaceStr.charAt(index);
                            }
                        }
                        mEditText.setText(contentStr);
                        mEditText.setSelection(contentStr.length());
                    }
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }

    }


    private void checkInput(EditText view1, EditText view2, EditText view3, EditText view4) {
        if (view1.length() == 0 || view2.length() == 0 || view3.length() != 3 || view4.length() == 0) {
            btn_pac.setEnabled(false);
        } else {
            btn_pac.setEnabled(true);
        }
    }
}
